//
//  XTXDengluViewController.m
//  jcb
//
//  Created by xcx on 2019/1/21.
//  Copyright © 2018年 jcb. All rights reserved.
//

#import "XTXDengluViewController.h"
#import "XTXRegiViewController.h"
#import "XTXTool.h"
#import "SDAutoLayout.h"
#import "UIImageView+WebCache.h"
#import "XTXNetworkingPageViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface XTXDengluViewController ()<UITextFieldDelegate>{
    MBProgressHUD *HUD;
    NSInteger index;//防止通知多次调用
    NSURL *url;
    NSString *url1;
}

@property (nonatomic,strong) UIImageView *bgImageView;//背景底图
@property (nonatomic,strong) UILabel *phoneLabel;//logo
@property (nonatomic,strong) UIButton *dengluBtn;//登录
@property (nonatomic,strong) UIView *line1;//线
@property (nonatomic,strong) UIImageView *phoneIconImageView;//手机图标
@property (nonatomic,strong) UIView *line2;//线
@property (nonatomic,strong) UIImageView *duanxinIconImageView;//短信图标
@property (nonatomic,strong) UITextField *phoneField;//手机输入框
@property (nonatomic,strong) UITextField *yanzhemaTextField;//验证码输入框
@property (nonatomic,strong) UIButton *getYanzhengmaBtn;//获取验证码
@property (nonatomic,strong) UIButton *xieyiBtn;//协议
@property (nonatomic, strong) UILabel *tempLabel1;

@end

@implementation XTXDengluViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    index =0;
    [self setUI];
    [self bujujiemian];
    [self createTips];
}
// 创建 Tips
- (void)createTips {
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:16];
    CGFloat tipW = (self.view.bounds.size.width - 17) / 16;
    CGFloat tipH = 5;
    CGFloat tipY = 1;
    for (int i = 0; i < 16; i++) {
        CGFloat tipX          = i * (tipW + 1) + 1;
        UIImageView *image    = [[UIImageView alloc] init];
        image.backgroundColor = [UIColor whiteColor];
        image.frame           = CGRectMake(tipX, tipY, tipW, tipH);
        [arr addObject:image];
    }
    [self updateLongView:[UIScreen mainScreen].brightness];
}

-(void)setUI {
    [self.view addSubview:self.bgImageView];
    [self.view addSubview:self.phoneLabel];
    [self.view addSubview:self.line1];
    [self.view addSubview:self.line2];
    [self.view addSubview:self.dengluBtn];
    [self.view addSubview:self.xieyiBtn];
    [self.view addSubview:self.tempLabel1];
    [self.line1 addSubview:self.phoneIconImageView];
    [self.line1 addSubview:self.phoneField];
    [self.line2 addSubview:self.duanxinIconImageView];
    [self.line2 addSubview:self.yanzhemaTextField];
    [self.line2 addSubview:self.getYanzhengmaBtn];
}
- (void)updateLongView:(CGFloat)sound {
    CGFloat stage = 1 / 15.0;
    NSInteger level = sound / stage;
    for (int i = 0; i < self.view.subviews.count; i++) {
        UIImageView *img = self.view.subviews[i];
        
        if (i <= level) {
            img.hidden = NO;
        } else {
            img.hidden = YES;
        }
    }
    
}


-(void)bujujiemian {
    self.phoneLabel.sd_layout
    .topSpaceToView(self.view, iOS_H(470))
    .leftSpaceToView(self.view, iOS_W(80))
    .rightEqualToView(self.view)
    .heightIs(iOS_H(70));
    
    self.line1.sd_layout
    .topSpaceToView(self.phoneLabel, iOS_H(80))
    .leftSpaceToView(self.view, iOS_W(80))
    .rightSpaceToView(self.view, iOS_W(80))
    .heightIs(60.0);
    
    self.line2.sd_layout
    .topSpaceToView(self.line1, iOS_H(40))
    .leftEqualToView(self.line1)
    .rightEqualToView(self.line1)
    .heightIs(60.0);
    
    self.phoneIconImageView.sd_layout
    .leftSpaceToView(self.line1, iOS_W(40))
    .centerYEqualToView(self.line1)
    .widthIs(iOS_W(36))
    .heightIs(iOS_H(40));
    
    self.phoneField.sd_layout
    .leftSpaceToView(self.phoneIconImageView, iOS_W(40))
    .centerYEqualToView(self.phoneIconImageView)
    .rightSpaceToView(self.line1, iOS_W(40))
    .heightIs(iOS_H(31));
    
    self.duanxinIconImageView.sd_layout
    .leftSpaceToView(self.line2, iOS_W(40))
    .centerYEqualToView(self.line2)
    .widthIs(iOS_W(34))
    .heightIs(iOS_H(40));
    
    self.yanzhemaTextField.sd_layout
    .leftSpaceToView(self.duanxinIconImageView, iOS_W(40))
    .centerYEqualToView(self.duanxinIconImageView)
    .rightSpaceToView(self.getYanzhengmaBtn, iOS_W(40))
    .heightIs(iOS_H(31));
    
    self.getYanzhengmaBtn.sd_layout
    .rightSpaceToView(self.line2, iOS_W(30))
    .centerYEqualToView(self.yanzhemaTextField)
    .widthIs(iOS_frame_width(180))
    .heightIs(iOS_frame_width(31));
    
    self.xieyiBtn.sd_layout
    .centerXEqualToView(self.view)
    .topSpaceToView(self.line2, iOS_H(24))
    .widthIs(App_Frame_Width)
    .heightIs(iOS_H(27));
    
    self.dengluBtn.sd_layout
    .topSpaceToView(self.line2, iOS_H(100))
    .centerXEqualToView(self.view)
    .widthIs(iOS_W(530))
    .heightIs(60.0);
        
    self.tempLabel1.sd_layout
    .leftEqualToView(self.view)
    .rightEqualToView(self.view)
    .bottomSpaceToView(self.view, iOS_H(30))
    .heightIs(30.0);
    
}
- (void)addNotification {

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(updateLayer:)
                                             name:UIDeviceOrientationDidChangeNotification
                                           object:nil];
   
}

//获取验证码
-(void)huoquyanzhengma {
    if (_phoneField.text.length == 11) {
        if ([XTXTool share].islianjiewangluo == 0) {
            [XTXTool showError:@"当前无网络"];
        }else{
            [self sendCode];
        }
    }else{
        [XTXTool showError:@"请输入正确的手机号"];
    }
}
- (void)addObserver {
    [[UIScreen mainScreen] addObserver:self
                            forKeyPath:@"brightness"
                               options:NSKeyValueObservingOptionNew context:NULL];
}
-(void)shoujidengluBtnClick {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"username"] = _phoneField.text;
    parameters[@"phonecode"] = _yanzhemaTextField.text;
    parameters[@"fromwhere"] = fromwhere;
    [[NetworkTool sharedTools]requestMethod:POST URL:[NSString stringWithFormat:@"%@%@",Portaddress,shoujidengludewangluojiekou] parameters:parameters finish:^(id responseObject, NSError *errpr) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self->HUD hideAnimated:YES afterDelay:0.1];
        });
        if ([responseObject[@"code"] isEqual:@"1"]) {
            XTXGongTool.share.useMode = [XTXUserModel yy_modelWithDictionary:responseObject[@"info"]];
            XTXTool.share.ConsumerModel = [ConsumerModel yy_modelWithDictionary:responseObject[@"info"]];
            XTXGongTool.share.useMode.momomo = @"0";
            [XTXGongTool baocungerenwangluqingiqushujuEventClick:XTXGongTool.share.useMode];
            [[NSUserDefaults standardUserDefaults] setObject:responseObject[@"info"][@"defaultimage"] forKey:@"defaultimage"];
            [[NSUserDefaults standardUserDefaults] setObject:responseObject[@"info"][@"single"] forKey:@"singleziduan"];
            [XTXGongView tianjiasuoyoudeTabdekongzhiqijiazaiEventClick];
        }
        else if ([responseObject[@"code"] isEqual:@"-1"]) {
            XTXUserModel *useMode = [[XTXUserModel alloc] init];
            useMode.token = responseObject[@"token"];
            useMode.id = responseObject[@"id"];
            useMode.headimage = responseObject[@"headimage"];
            useMode.nickname = responseObject[@"nickname"];
            useMode.sex = responseObject[@"sex"];
            useMode.birthday = responseObject[@"birthday"];
            [[NSUserDefaults standardUserDefaults] setObject:responseObject[@"token"] forKey:@"yonghuToken"];
            useMode.defaultimage = responseObject[@"defaultimage"];
            useMode.photonum = self.phoneField.text;
            useMode.codeNum = self.yanzhemaTextField.text;
            XTXRegiViewController *zhuceViewC = [[XTXRegiViewController alloc] init];
            zhuceViewC.useMode = useMode;
            [self.navigationController pushViewController:zhuceViewC animated:YES];
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (errpr) {
                    [XTXGongView showTipMsg:@"当前网络不稳定，请稍后再试！"];
                }
                else {
                    [XTXGongView showTipMsg:responseObject[@"msg"]];
                }
            });
        }
    }];
    
}
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
    
    CGFloat sound = [change[@"new"] floatValue];
    [self appearSoundView];
    [self updateLongView:sound];
}

//登录
-(void)denglutishikuang
{
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.mode = MBProgressHUDModeIndeterminate;
    HUD.label.text = @"正在登录...";
    HUD.removeFromSuperViewOnHide = YES;
    [HUD hideAnimated:YES afterDelay:10.0];
    [self shoujidengluBtnClick];
}
- (void)updateLayer:(NSNotification *)notify {
    NSLog(@"%@",notify.userInfo);
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.phoneField) {
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength > 11) {
            return NO;
        }
    }
    if (textField == self.yanzhemaTextField) {
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength > 6) {
            return NO;
        }
    }
    
    return YES;
}
- (void)appearSoundView {
    if (self.view.alpha == 0.0) {
//        self.orientationDidChange = NO;
        self.view.alpha = 1.0;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self disAppearSoundView];
        });
    }
}
-(void)xieyiBtnClick
{
    XTXNetworkingPageViewController *web=[[XTXNetworkingPageViewController alloc]init];
    web.dizhiStr=xieyiUrl;
    [self.navigationController pushViewController:web animated:YES];
}
- (void)disAppearSoundView {
    
    if (self.view.alpha == 1.0) {
        [UIView animateWithDuration:0.8 animations:^{
            self.view.alpha = 0.0;
        }];
    }
    [self changeResolution:nil];
}
-(void)dingshiqishiajingaibain
{
    __block NSInteger time = 59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(time <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置按钮的样式
                [self.getYanzhengmaBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                self.getYanzhengmaBtn.userInteractionEnabled = YES;
            });
        }else{
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置按钮显示读秒效果
                [self.getYanzhengmaBtn setTitle:[NSString stringWithFormat:@"已发送(%.2dS)", seconds] forState:UIControlStateNormal];
                self.getYanzhengmaBtn.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}
- (void)changeResolution:(UIButton *)sender {
    sender.selected = YES;
    if (sender.isSelected) {
        sender.backgroundColor =UIColor.orangeColor;
    } else {
        sender.backgroundColor = [UIColor clearColor];
    }
    // 隐藏分辨率View
   sender.hidden  = YES;
    // 分辨率Btn改为normal状态
    sender.selected = NO;
    // topImageView上的按钮的文字
    [sender setTitle:sender.titleLabel.text forState:UIControlStateNormal];
    [self tapSliderAction:nil];
}
-(UIImageView *)bgImageView{
    if (!_bgImageView) {
        _bgImageView = [UIImageView new];
        _bgImageView.frame = CGRectMake(0, 0, App_Frame_Width, APP_Frame_Height);
        _bgImageView.image = [UIImage imageNamed:@"手机登陆页底图"];
        _bgImageView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _bgImageView;
}
 -(void)tapSliderAction:(UITapGestureRecognizer *)tap {
    if ([tap.view isKindOfClass:[UISlider class]]) {
        UISlider *slider = (UISlider *)tap.view;
        CGPoint point = [tap locationInView:slider];
        CGFloat length = slider.frame.size.width;
        // 视频跳转的value
        CGFloat tapValue = point.x / length;
        [self  lockScrrenBtnClick:nil];
    }
}

- (UILabel *)phoneLabel
{
    if (!_phoneLabel) {
        _phoneLabel = [[UILabel alloc] init];
        _phoneLabel.text = @"手机登录";
        _phoneLabel.textColor = XZRGB(0xafaec4);
        _phoneLabel.font = [UIFont systemFontOfSize:35.0];
    }
    return _phoneLabel;
}
- (void)lockScrrenBtnClick:(UIButton *)sender {
    sender.selected = !sender.selected;
}

-(UIImageView *)phoneIconImageView{
    if (!_phoneIconImageView) {
        _phoneIconImageView = [UIImageView new];
        _phoneIconImageView.image = [UIImage imageNamed:@"用户手机号码"];
    }
    return _phoneIconImageView;
}

-(UIImageView *)duanxinIconImageView{
    if (!_duanxinIconImageView) {
        _duanxinIconImageView = [UIImageView new];
        _duanxinIconImageView.image = [UIImage imageNamed:@"验证码"];
    }
    return _duanxinIconImageView;
}

-(UIView *)line1{
    if (!_line1) {
        _line1 = [UIView new];
        _line1.layer.borderColor = XZColor(230, 230, 230).CGColor;
        _line1.layer.borderWidth = 0.5;
        _line1.layer.cornerRadius = 30.0;
    }
    return _line1;
}

-(UIView *)line2{
    if (!_line2) {
        _line2 = [UIView new];
        _line2.layer.borderColor = XZColor(230, 230, 230).CGColor;
        _line2.layer.borderWidth = 0.5;
        _line2.layer.cornerRadius = 30.0;
        
    }
    return _line2;
}

-(UITextField *)yanzhemaTextField{
    if (!_yanzhemaTextField) {
        _yanzhemaTextField = [UITextField new];
        _yanzhemaTextField.textColor = [UIColor blackColor];
        _yanzhemaTextField.delegate = self;
        _yanzhemaTextField.clearButtonMode = UITextFieldViewModeAlways;
        _yanzhemaTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;//首字母是否大写
        _yanzhemaTextField.placeholder = @"输入验证码";
        _yanzhemaTextField.keyboardType = UIKeyboardTypeNumberPad;
        _yanzhemaTextField.font = [UIFont systemFontOfSize:iOS_frame_width(30)];
    }
    return _yanzhemaTextField;
}

-(UITextField *)phoneField{
    if (!_phoneField) {
        _phoneField = [UITextField new];
        _phoneField.textColor =[UIColor blackColor];
        _phoneField.delegate = self;
        _phoneField.placeholder = @"输入手机号码";
        _phoneField.clearButtonMode = UITextFieldViewModeAlways;
        _phoneField.autocapitalizationType = UITextAutocapitalizationTypeNone;//首字母是否大写
        _phoneField.keyboardType = UIKeyboardTypeNumberPad;
        _phoneField.font = [UIFont systemFontOfSize:iOS_frame_width(30)];
    }
    return _phoneField;
}

-(UIButton *)getYanzhengmaBtn{
    if (!_getYanzhengmaBtn) {
        _getYanzhengmaBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_getYanzhengmaBtn setTitle:@"获取" forState:(UIControlStateNormal)];
        _getYanzhengmaBtn.titleLabel.font = [UIFont systemFontOfSize:iOS_frame_width(30)];
        [_getYanzhengmaBtn setTitleColor:XZColor(255,121,121) forState:UIControlStateNormal];
        _getYanzhengmaBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [_getYanzhengmaBtn addTarget:self action:@selector(huoquyanzhengma)forControlEvents:UIControlEventTouchUpInside];
    }
    return _getYanzhengmaBtn;
}

-(UIButton *)dengluBtn{
    if (!_dengluBtn) {
        _dengluBtn = [UIButton new];
        [_dengluBtn setBackgroundImage:[UIImage imageNamed:@"手机登录页-登陆底图"] forState:UIControlStateNormal];
        [_dengluBtn addTarget:self action:@selector(denglutishikuang) forControlEvents:UIControlEventTouchUpInside];
        [_dengluBtn setTitle:@"登录" forState:UIControlStateNormal];
        [_dengluBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
    return _dengluBtn;
}

-(UIButton *)xieyiBtn{
    if (!_xieyiBtn) {
        _xieyiBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:@"登录即同意《用户协议》"];
        //此时如果设置字体颜色要这样
        [title addAttribute:NSForegroundColorAttributeName value:XZColor(210, 210, 210) range:NSMakeRange(0,5)];
        [title addAttribute:NSForegroundColorAttributeName value:XZColor(255, 121, 121) range:NSMakeRange(5,6)];
        _xieyiBtn.contentHorizontalAlignment =UIControlContentHorizontalAlignmentCenter;
        _xieyiBtn.titleLabel.font = ICFont(iOS_H(26));
        [_xieyiBtn setAttributedTitle:title forState:UIControlStateNormal];
        [_xieyiBtn addTarget:self action:@selector(xieyiBtnClick) forControlEvents:UIControlEventTouchUpInside];
        _xieyiBtn.hidden = YES;
        _xieyiBtn.userInteractionEnabled=YES;
    }
    return _xieyiBtn;
}

- (UILabel *)tempLabel1
{
    if (!_tempLabel1) {
        _tempLabel1 = [[UILabel alloc] init];
        _tempLabel1.text = @"禁止未满18周岁用户注册使用";
        _tempLabel1.textAlignment = NSTextAlignmentCenter;
    }
    return _tempLabel1;
}

-(UIImage *)thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSAssert(asset,@"非法参数");
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60) actualTime:NULL error:&thumbnailImageGenerationError];
    
    if (!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@", thumbnailImageGenerationError);
    
    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef] : nil;
    return thumbnailImage;
}

- (void)sendCode
{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"username"] = _phoneField.text;
    
    [[NetworkTool sharedTools] requestMethod:POST URL:[NSString stringWithFormat:@"%@%@",Portaddress,huoqushoujiyanzhengmadewangluojiekou] parameters:parameters finish:^(id responseObject, NSError *errpr) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([responseObject[@"code"] integerValue] == 1) {
                [self dingshiqishiajingaibain];
                [XTXTool showError:responseObject[@"msg"]];
            }
            else {
                [XTXTool showError:responseObject[@"msg"]];
            }
        });
    }];
}

@end
